<template>
  <div>
    <n-card title="用户管理">
      <template #header-extra>
        <n-space>
          <n-input
            v-model:value="keyword"
            placeholder="搜索用户"
            clearable
            @clear="loadUsers"
          >
            <template #suffix>
              <n-button text @click="loadUsers">
                <n-icon><SearchOutline /></n-icon>
              </n-button>
            </template>
          </n-input>
          <n-select
            v-model:value="roleFilter"
            placeholder="角色筛选"
            :options="roleOptions"
            clearable
            style="width: 150px"
            @update:value="loadUsers"
          />
        </n-space>
      </template>

      <n-data-table
        :columns="columns"
        :data="users"
        :pagination="pagination"
        :loading="loading"
      />
    </n-card>
  </div>
</template>

<script setup>
import { ref, reactive, h, onMounted } from 'vue'
import { NButton, NSpace, NTag, NSwitch } from 'naive-ui'
import { getUserList, toggleUserStatus } from '@/api/user'
import { SearchOutline } from '@vicons/ionicons5'

const loading = ref(false)
const users = ref([])
const keyword = ref('')
const roleFilter = ref(null)

const pagination = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 30, 50],
  onChange: (page) => {
    pagination.page = page
    loadUsers()
  },
  onUpdatePageSize: (pageSize) => {
    pagination.pageSize = pageSize
    pagination.page = 1
    loadUsers()
  }
})

const roleOptions = [
  { label: '管理员', value: 'ADMIN' },
  { label: '志愿者', value: 'VOLUNTEER' }
]

const columns = [
  { title: 'ID', key: 'id', width: 80 },
  { title: '用户名', key: 'username' },
  { title: '昵称', key: 'nickname' },
  { title: '手机号', key: 'phone' },
  { title: '邮箱', key: 'email' },
  { 
    title: '角色', 
    key: 'role',
    render: (row) => {
      return h(NTag, { 
        type: row.role === 'ADMIN' ? 'error' : 'success'
      }, { 
        default: () => row.role === 'ADMIN' ? '管理员' : '志愿者'
      })
    }
  },
  { 
    title: '状态', 
    key: 'status',
    render: (row) => {
      return h(NSwitch, {
        value: row.status === 1,
        onUpdateValue: () => handleToggleStatus(row.id)
      })
    }
  },
  { 
    title: '创建时间', 
    key: 'createTime',
    render: (row) => new Date(row.createTime).toLocaleString('zh-CN')
  }
]

const loadUsers = async () => {
  loading.value = true
  try {
    const res = await getUserList({
      page: pagination.page,
      size: pagination.pageSize,
      keyword: keyword.value,
      role: roleFilter.value
    })
    users.value = res.data.records || []
    pagination.itemCount = res.data.total || 0
  } catch (error) {
    console.error('加载用户列表失败:', error)
  } finally {
    loading.value = false
  }
}

const handleToggleStatus = async (userId) => {
  try {
    await toggleUserStatus(userId)
    window.$message?.success('操作成功')
    loadUsers()
  } catch (error) {
    console.error('操作失败:', error)
  }
}

onMounted(() => {
  loadUsers()
})
</script>

